package stephen.jan21;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;






public class UserDao {
  Connection con=null;
  PreparedStatement ps=null;
  ResultSet rs=null;
  BaseDao baseDao=new BaseDao();
  public User getUserbyName(String name) throws SQLException{
	  con=baseDao.getCon();
	  String sql="select*from user where username=?";
	  ps=con.prepareStatement(sql);
	  ps.setString(1, name);
	  rs=ps.executeQuery();
	 
	  String pwd="";
	  while(rs.next()){
		  pwd=rs.getString("pwd");
		  
	  }
	  
	 User u=new User();
	 u.setPwd(pwd);
	 u.setUsername(name);
	 if(rs!=null){rs.close();}
	 if(ps!=null){ps.close();}
	 if(con!=null){con.close();}
     return u;
     
     
  }
  
  public boolean registered(String name,String pwd) throws SQLException{	
		boolean result=false;
		con=baseDao.getCon();
		
		User u=new User();
		u.setUsername(name);
		u.setPwd(pwd);
		String sql="SELECT * FROM user WHERE userName=?";
		String sql1="INSERT INTO user (userName,pwd) VALUES ('"+u.getUsername()+"','"+u.getPwd()+"')";
		ps=con.prepareStatement(sql);
		ps.setString(1, name);
		rs=ps.executeQuery();
	
		try {
			
			if(rs.next()){
				
				
			}else{
				con=baseDao.getCon();
				ps=con.prepareStatement(sql1);
			
				rs=ps.executeQuery();
				System.out.println("注册成功");
				result=true;}
			if(rs!=null){
				rs.close();
			}
			if(ps!=null){
				ps.close();
				
			}
			if(con!=null){
				con.close();
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		return result;
	}
  
  
  
  public static void main(String[] args){
	  UserDao ud=new UserDao();
	  
		  User u;
		try {
			u = ud.getUserbyName("cj");
			 System.out.println(u.getPwd());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  
		try {
			ud.registered("jj","123");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  
  }
}
